{include "INC_header.html" title="分类编辑"}
<div id="app-outlet" class="app-outlet">
    <!-- ant-design 应用需要配置 -->
    <a-config-provider :locale="config.locale" :theme="config.theme">
        <div class="app-container">
            <main class="padding">
                <div class="ui message info">
                    <i class="fa fa-info-circle"></i> 分类可设置为站点通用，或指定站点，暂不支持指定多个站点。如果有选择父级分类，站点归属以父级分类为准！
                </div>
                <div class="ui form margin-top">
                    <div class="field">
                        <div class="label">站点归属</div>
                        <div class="">
                            <a-radio-group v-model:value="data.multiSite" button-style="solid" @change="updateMultiSite">
                                <a-radio :value="0">通用</a-radio>
                                <a-radio :value="1">指定站点</a-radio>
                            </a-radio-group>
                        </div>
                    </div>
                    <div class="field" v-if="data.multiSite == 1">
                        <div class="label">指定站点归属</div>
                        <div class="">
                            <a-checkbox v-model:checked="es.checked" v-for="es in sites" :value="es.id" @change="updateSiteId">{{ es.name }}</a-checkbox>
                        </div>
                    </div>
                    <div class="ui message info margin-top">
                        <i class="fa fa-info-circle"></i> 父级分类会根据站点归属而变动，如果站点重新指定后，需要注意父级分类也会跟着变动，需要重新选择！
                    </div>
                    <div class="field">
                        <div class="ui flex-item padding-bottom-half">
                            <div class="start text-bold">选择父级分类：</div>
                            <div class="center">
                                <div class="ui breadcrumb">
                                    <div class="item" v-for="n in catNames" style="font-weight: normal!important;">{{ n }}</div>
                                </div>
                            </div>
                        </div>
                        <div class="ui multi-selector">
                            <div class="options" v-for="(categories, idx1) of categoryList">
                                <div class="option ui flex-item" :class="{ selected: category.selected, disabled:category.id==data.id }" v-for="(category, idx2) of categories" @click="selectCategory(idx1, idx2, category)">
                                    <div class="center">{{ category.name }}</div>
                                    <div class="end justify-center">
                                        <i class="fa-solid fa-caret-right"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="fields padding-top">
                        <div class="field">
                            <div class="label">分类名称</div>
                            <div class="">
                                <a-input style="width: 200px;" v-model:value="data.name" placeholder="必填"></a-input>
                            </div>
                        </div>
                        <div class="field">
                            <div class="label">索引</div>
                            <div class="">
                                <a-input style="width: 200px;" v-model:value="data.index" placeholder="选填，可用于数据调取"></a-input>
                            </div>
                        </div>
                    </div>
                    <!-- 图集 -->
                    <div class="field">
                        <div class="ui flex-item padding-bottom-half">
                            <div class="start text-bold">图集</div>
                            <div class="center medium-text"><i class="fa fa-info-circle"></i> 第一张图片将作为预览图</div>
                        </div>
                        <div class="ui images padding-half light-background">
                            <div class="image" v-for="(image, index) in data.pictures">
                                <img :src="image">
                                <!-- 移除按钮 -->
                                <div class="remove" @click="deletePicture(index)"><i class="fa-solid fa-xmark"></i></div>
                            </div>
                            <div class="image plus" @click="addPicture">
                                <i class="fa-solid fa-plus text-bigger"></i>
                                <div class="padding-top">添加图片</div>
                            </div>
                        </div>
                    </div>
                    <div class="field">
                        <div class="ui flex-item padding-bottom-half">
                            <div class="start text-bold">分类详情</div>
                            <div class="center medium-text"><i class="fa fa-info-circle"></i> 可用作单页展示</div>
                        </div>
                        <textarea id="detailEditor" name="detail" style="height: 500px;"></textarea>
                    </div>
                    <!-- 关键词 -->
                    <div class="field">
                        <div class="label">分类页面关键词</div>
                        <div class="">
                            <a-input placeholder="关键词，SEO可用" v-model:value="data.keyword"></a-input>
                        </div>
                    </div>
                    <!-- 摘要 -->
                    <div class="field">
                        <div class="label">分类页面摘要</div>
                        <div class="">
                            <a-textarea rows="3" placeholder="页面摘要，SEO可用" v-model:value="data.description"></a-textarea>
                        </div>
                    </div>
                    <div class="fields padding-top">
                        <div class="field" style="width: 200px;">
                            <div class="label">自定义分类页模板</div>
                            <div class="">
                                <a-input v-model:value="data.template" placeholder="文件名"></a-input>
                            </div>
                        </div>
                        <div class="field" style="width: 200px;">
                            <div class="label">自定义文章页模板</div>
                            <div class="">
                                <a-input v-model:value="data.templateArchive" placeholder="文件名"></a-input>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
            <footer class="light-background padding border-top ui flex-item">
                <div class="center"></div>
                <div class="end">
                    <a-button href="{url url='/cms/admin/category/list'}"><i class="fa fa-arrow-left margin-right-half"></i> 返回列表</a-button>
                </div>
                <div class="end">
                    <a-button type="primary" @click="save"><i class="fa-regular fa-floppy-disk margin-right-half"></i> 保存分类</a-button>
                </div>
            </footer>
        </div>
        <!-- 文件选择器 -->
        <a-modal class="iframe-body"
                 v-model:visible="filesModal.show"
                 :title="filesModal.title"
                 :cancel-text="filesModal.cancelText"
                 :ok-text="filesModal.okText"
                 @ok="filesManagerOk">
            <iframe ref="filesFrame" v-if="filesModal.show" :src="filesModal.fs + '&resize=' + filesModal.resize + '&type=' + filesModal.type + '&multi=' + (filesModal.multi ? 1 : 0)" frameborder="0" scrolling="auto" width="100%" height="100%"></iframe>
        </a-modal>
    </a-config-provider>
</div>
{include "INC_UEditor.html"}
<script>
    let detailEditor = UE.getEditor("detailEditor");
    //vue app
    const { createApp, defineComponent, ref } = Vue;
    const { message, Modal } = antd;
    const app = createApp({
        data() {
            return {
                //主题配置
                config: appProviderConfig,
                id: parseInt("{$get.id|default:0}"),
                //已选
                parentsId: '',
                //已选名称
                catNames: ["顶级分类"],
                //可选列
                categoryList: [
                    [
                        {
                            id: 0,
                            name: '顶级分类',
                            selected: true
                        }
                    ]
                ],
                data: {
                    id: 0,
                    parentId: 0,
                    parentsId: null,
                    name: '',
                    index: '',
                    keyword: '',
                    description: '',
                    detail: '',
                    siteId: null,
                    multiSite: 0,
                    pictures: [],
                    template: '',
                    templateArchive: ''
                },
                //文件管理器
                filesModal: {
                    show: false,
                    title: "文件选择",
                    okText: "确定",
                    cancelText: "取消",
                    ok: null,
                    fs: "{url url='/fs'}?parentId=0&groupName=cms&selectable=1",
                    resize: "",
                    type: "all",
                    multi: false
                },
                //当前选择的站点ID
                sites: []
            }
        },
        mounted() {
            let self = this;
            const hide = message.loading("正在加载站点数据");
            axios.get("{url url='/cms/api/site/list'}", {
                params: { admin:1, total: 500 }
            }).then(({ data }) => {
                hide();
                if (data.error === 0) {
                    let sites = data.data.list;
                    sites.map(site => {
                        site.checked = false;
                    });
                    self.sites = sites;
                    //挂载成功
                    this.initData();
                } else {
                    message.error(data.message);
                }
            }).catch(() => {
                hide();
                message.error("加载数据失败");
            });
        },
        methods: {
            //初始化数据
            initData() {
                let self = this;
                //获取栏目详情
                if (self.id > 0) {
                    const hide = message.loading("正在加载数据...", 0);
                    axios.get("{url url='/cms/api/category'}", {
                        params: {
                            admin: 1,
                            id: self.id
                        }
                    }).then(({ data }) => {
                        hide();
                        if (data.error === 0) {
                            data.data.multiSite = data.data.siteId != '' && data.data.siteId != null && data.data.siteId != '0' ? 1 : 0;
                            self.parentsId = data.data.parentsId;
                            self.data = data.data;
                            //处理siteId
                            if (data.data.multiSite === 1) {
                                let siteId = self.data.siteId.split(",");
                                self.sites.forEach(site => {
                                    site.checked = siteId.indexOf(site.id.toString()) !== -1;
                                });
                            }
                            //加载编辑器
                            detailEditor.ready(() => {
                                detailEditor.setContent(data.data.detail || '<p></p>');
                            });
                            //处理已选择的父级
                            this.getCategories(0);
                        } else {
                            Modal.error({
                                title: '错误',
                                content: data.message,
                            });
                        }
                    }).catch(() => {
                        hide();
                        message.error("服务端繁忙");
                    });
                } else {
                    //获取第一层
                    this.getCategories(0);
                }
            },
            selectCategory(idx1, idx2, category) {
                if (category.id == this.data.id) {
                    return;
                }
                let self = this;
                self.categoryList[idx1].map(item => {
                    item.selected = item.id == category.id;
                });
                if(this.categoryList.length > idx1 + 1){
                    this.categoryList.splice(idx1 + 1);
                    this.catNames.splice(idx1 + 1);
                }
                this.catNames[idx1] = category.name;
                this.data.parentId = category.id;
                //如果点击过一次了，不再以数据的为准
                this.parentsId = '';
                //获取下一级列表
                this.getCategories(category.id);
            },
            getCategories(parentId) {
                //获取第一层
                let self = this;
                axios.get("{url url='/cms/api/category/list'}", {
                    params: {
                        parentId,
                        admin: 1,
                        siteId: this.data.siteId
                    }
                }).then(({ data }) => {
                    if(data.error === 0){
                        if(data.data.length > 0){
                            let parentsId = self.parentsId;
                            if(parentsId !== '0' && parentsId !== '' && parentsId !== null && parentsId.toString().length > 0) {
                                parentsId = parentsId.split(",");
                                data.data.forEach(item => {
                                    if(parentsId.indexOf(item.id.toString()) !== -1) {
                                        item.selected = true;
                                        self.catNames.push(item.name);
                                        self.getCategories(item.id);
                                    }
                                });
                            }
                            self.categoryList.push(data.data);
                        }
                    }
                }).catch(() => {
                    message.error("无法获取分类");
                });
            },
            updateMultiSite() {
                this.data.siteId = null;
                this.data.parentId = 0;
                this.sites.map(site => {
                    site.checked = false;
                });
                this.updateSiteId();
            },
            //站点ID变动
            updateSiteId() {
                let siteId = [];
                this.sites.map(site => {
                    if(site.checked) {
                        siteId.push(site.id);
                    }
                });
                this.data.siteId = siteId.join(",");
                //重新取可用分类
                this.parentsId = '';
                this.catNames = ['顶级分类'];
                this.data.parentId = 0;
                this.categoryList = this.categoryList.slice(0, 1);
                this.getCategories(0);
            },
            //打开文件管理对话框
            filesManagerOpen: function (params) {
                params = params || {};
                this.filesModal.title = params.title || "文件选择";
                this.filesModal.okText = params.okText || "确定";
                this.filesModal.cancelText = params.cancelText || "取消";
                this.filesModal.resize = params.resize || "";
                this.filesModal.type = params.type || "all";
                this.filesModal.multi = params.multi || false;
                this.filesModal.ok = params.ok || null;
                this.filesModal.show = true;
            },
            //点击确定
            filesManagerOk: function () {
                //从iFrame里边找图片
                let filesManager = this.$refs.filesFrame.contentWindow.FilesManager || {};
                if (filesManager.list) {
                    let list = [];
                    filesManager.list.map(file => {
                        if (file.checked && (this.filesModal.type === "all" || file.type === this.filesModal.type)) {
                            list.push(file);
                        }
                    });
                    if (list.length > 0 && typeof this.filesModal.ok === "function") {
                        this.filesModal.ok(this.filesModal.multi ? list : list[0]);
                    }
                }
                //关闭文件选择框
                this.filesModal.show = false;
            },
            addPicture() {
                let self = this;
                this.filesManagerOpen({
                    title: '添加分类图集',
                    type: 'image',
                    multi: true,
                    ok: images => {
                        images.map(image => {
                            self.data.pictures.push(image.url);
                        });
                    }
                });
            },
            deletePicture(index) {
                this.data.pictures.splice(index, 1);
            },
            //保存
            save() {
                if (this.data.name.toString().length < 1) {
                    return message.error("缺少分类名称");
                }
                //处理HTML内容
                const category = {
                    id: this.data.id,
                    siteId: this.data.siteId,
                    parentId: this.data.parentId,
                    name: this.data.name,
                    index: this.data.index,
                    keyword: this.data.keyword,
                    description: this.data.description,
                    detail: detailEditor.getContent(),
                    pictures: this.data.pictures.join(","),
                    template: this.data.template,
                    templateArchive: this.data.templateArchive
                };
                const hide = message.loading("正在保存...", 0);
                axios.post("{url url='/cms/api/category/save'}", category).then(({ data }) => {
                    hide();
                    if (data.error === 0) {
                        window.location.href = "{url url='/cms/admin/category/list'}";
                    } else {
                        message.error(data.message);
                    }
                }).catch(() => {
                    hide();
                    message.error('服务端繁忙');
                });
            }
        }
    }).use(antd);
    //挂载
    const vm = app.mount("#app-outlet");
    //
    if (window.parent) {
        window.parent.postMessage({
            event: "location",
            data: [
                { name:"文章分类管理" },
                { name:"编辑分类" }
            ]
        });
    }
</script>
{include "INC_footer.html"}